package com.ant.common.utils;

import com.ant.business.system.vo.UserVo;
import com.ant.common.exceptions.BusinessException;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 通过ThreadLocal获取用户信息
 * @author LB
 */
public class UserThreadLocal {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static String LOGIN_USER = "LOGIN_USER";

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key){
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }


    public static void setUser(UserVo admin){
        if (Objects.isNull(admin)){
            set(LOGIN_USER, new UserVo());
        }else {
            set(LOGIN_USER, admin);
        }
    }

    @SneakyThrows
    public static UserVo getUser(){
        Object o = get(LOGIN_USER);
        if (Objects.isNull(o)){
            throw new BusinessException("用户未登录，请重新登录");
        }else {
            return (UserVo) get(LOGIN_USER);
        }
    }

}
